package com.java1412;

/**
 * @author java1412
 * @create 2022-09-21 16:56
 */
public class Test3 {
    public static void main(String[] args) {
        Runnable r = new MyRunnable2();
        Thread t1 = new Thread(r, "抢票代理");
        Thread t2 = new Thread(r, "淘票票");
        Thread t3 = new Thread(r, "黄牛党");
        t1.start();
        t2.start();
        t3.start();
    }
}

class Stock {
    public static int ticket = 10; // 原始10张票
}

class MyRunnable2 implements Runnable {
    private boolean flag = true;

    //    @Override
    //    public synchronized void run() {
    public void run() {
        while (flag) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                if (Stock.ticket <= 0) {
                    break;
                }
                Stock.ticket--;
                System.out.println(Thread.currentThread().getName() + "抢到第" + (10 - Stock.ticket) + "张票，剩余" + Stock.ticket + "张票!");
            }
            if (Thread.currentThread().getName().equals("黄牛党")) {
                flag = false;
            } else {
                flag = true;
            }
        }
    }
}
